package demo.customer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import demo.MyConfiguration;
import demo.customer.service.AccountService;
import demo.model.CustomerResponseModel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;


@RestController
@RequestMapping("/customer")
@AllArgsConstructor
@NoArgsConstructor
public class CustomerServiceController {
	
	@Autowired
	private MyConfiguration configuration;
	
	@Autowired
	private AccountService accountService;
		
//	public CustomerServiceController(@Autowired MyConfiguration configuration) {
//		this.configuration = configuration;
//	}
	
//	public CustomerServiceController(@Autowired MyConfiguration configuration, @Autowired AccountService accountService) {
//		this.configuration = configuration;
//		this.accountService = accountService;
//	}
//    @Autowired
//    RestTemplate restTemplate;
    
    @PreAuthorize("hasRole('ADMIN')")
	@RequestMapping(value = "admingreeting", method = RequestMethod.GET)
	public String greeting() {
		return "(ADMIN)Greeting from " + configuration.getServiceId();
    }
    
    @PreAuthorize("hasRole('USER')")
	@RequestMapping(value = "greeting", method = RequestMethod.GET)
	public String greeting2() {
		return "(USER)Greeting from " + configuration.getServiceId();
    }
    
    @RequestMapping(value="/{name}/accounts")
    public ResponseEntity<CustomerResponseModel> getAccounts(@PathVariable String name,@RequestParam String region) {
    	
    	CustomerResponseModel response = new CustomerResponseModel();
    	
    	response.setServiceId(configuration.getServiceId());
    	
//    	try {    	
//	    	Object accounts = this.restTemplate.getForObject("http://account-service-ribbon/account/list?name={name}&region={region}", Object.class, name,region); 
//	    	response.setPayload(accounts);
//    	}
//    	catch(Exception e) {
//    		//fallback message
//    		response.setPayload("account-service is unavailable");
//    	}
    	
    	response.setPayload(accountService.getAccounts(name, region));
    	
//    	try {
//	    	List txn = this.restTemplate.getForObject("http://txn-service-ribbon/txn/list?name={name}&region={region}", ArrayList.class,name,region);	    	
//	    	results.put("txn", txn);
//    	}catch(Exception e) {
//    		//fallback message
//    		results.put("txn", "txn-service is unavailable");
//    	}
    	
    	return ResponseEntity.ok(response);    	
    }    
}
